17. Spring Beans and Dependency Injection(Spring Beans和依赖注入)
1 | You are free to use any of the standard Spring Framework |
您可以自由的使用Spring框架标注的一些技术和注解来定义您的注入依赖关系。打个比方,我们经常使用
@ComponentScan(去查找您的beans),用@Autowired(去做构造注入)。
1 | If you structure your code as suggested above (locating your |
如果您按照以上的建议构造您的代码结构(将您的主应用类放在根包下面),您可以增加@ComponentScan注解而不需要任何参数。您所有的应用组件(@Component, @Service, @Repository, @Controller 等等)都将被自动注册为Spring Beans。
1 | The following example shows a @Service Bean that uses |
接下去的例子展示了@Service使用构造注入去获得必要的RiskAssessor bean1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
1 | If a bean has one constructor, you can omit the @Autowired, |
如果一个bean有一个构造函数,您可以省略@Autowired注解,如下例子:1
2
3
4
5
6
7
8
9
10
11
12
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
1 | Notice how using constructor injection lets the riskAssessor |
注意介绍如何使用构造注入使riskAssessor字段被标记为final,表明它不可以随后改变。